﻿using System;
using System.Configuration;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class McAccountsController : BaseController
    {
        private readonly McAccountsBLL _bll = new McAccountsBLL();
        private readonly McAccountRoleBLL _arBll = new McAccountRoleBLL();

        public ActionResult Create(int id)
        {
            if (id < 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var model = new McAccounts {ShopId = id};
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, McAccounts model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var mkysMcProjectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (mkysMcProjectInfo == null || mkysMcProjectInfo.Id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var mkysProjectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcId);
            if (mkysProjectInfo == null || mkysProjectInfo.Id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            model.PasswordHash = EncryptionLib.Encrypt(model.PasswordHash);
            model.AccountType = 1; // 店铺账号
            model.LockoutEnabled = false;
            model.LockoutUntil = DateTime.Now;
            model.AccessFailedCount = 0;
            model.IsMagAccount = false;
            model.CreatedBy = 0;
            model.UpdatedBy = 0;
            model.Created = DateTime.Now;
            model.Updated = DateTime.Now;
            model.MxProjectInfoId = mkysMcProjectInfo.Id;

            int result = _bll.AddWithQrParam(model, mkysProjectInfo);

            if (result <= 0) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);

            if (!string.IsNullOrEmpty(model.Mobile))
            {
                var sendContent = string.Format(ConfigurationManager.AppSettings["SendContent"], model.UserName, EncryptionLib.Decrypt(model.PasswordHash));
                SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.Mag, CommonEnum.SmsRecordUserActionSource.AddBoss);
            }

            var arModel = new McAccountRole {AccountId = result, RoleId = 1, IsDelete = false};
            _arBll.Add(arModel);

            return RedirectToAction("List", "Shops");
        }

        public ActionResult Update(int id)
        {
            if (id <= 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            var model = _bll.GetModel(id);
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.NotFound);

            //var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            //if (projectInfo == null || projectInfo.Id == 0)
            //{
            //    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            //}

            var mkysProjectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcId);
            if (mkysProjectInfo == null || mkysProjectInfo.Id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var resultQrCode = MatrixCloudCenterInterFuncBllobj.GetParamQrCodeById(model.MxWechatParamQrCodeId,
                mkysProjectInfo.PjMcId, mkysProjectInfo.PjSecret);

            if (resultQrCode.Status && resultQrCode.Data != null)
                ViewBag.QrCodePath = resultQrCode.Data.LocalQrCodePath;
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, McAccounts model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            var oriAccount = _bll.GetModel(model.Id);
            var oldMobile = oriAccount.Mobile;
            if (!string.IsNullOrEmpty(model.PasswordHash))
            {
                oriAccount.PasswordHash = EncryptionLib.Encrypt(model.PasswordHash);
            }
            oriAccount.Mobile = model.Mobile;
            oriAccount.DisplayName = model.DisplayName;
            oriAccount.IsDelete = model.IsDelete;
            oriAccount.UpdatedBy = CurrentUser.Id;
            oriAccount.Updated = DateTime.Now;
            var result = _bll.Update(oriAccount);
            if (result)
            {
                //更改手机号或者密码，发送短信
                if (!string.IsNullOrEmpty(model.Mobile) && (!string.IsNullOrEmpty(model.PasswordHash) || oriAccount.Mobile != oldMobile))
                {
                    var sendContent = string.Format(ConfigurationManager.AppSettings["SendContent"], oriAccount.UserName, EncryptionLib.Decrypt(oriAccount.PasswordHash));
                    SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.Mag, CommonEnum.SmsRecordUserActionSource.ModifyBoss);
                }
                return RedirectToAction("List", "Shops");
            }
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #region 账户唯一验证
        /// <summary>
        /// 检查重复数据
        /// </summary>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult ValidateUserName(string userName, int accountId)
        {
            var resultMessage = _bll.CheckUserNameAvailable(userName, accountId);
            return Json(resultMessage);
        }
        #endregion

        /// <summary>
        /// 所有数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetCount()
        {
            var data = _bll.GetModelList().Count;

            return Json(data);
        }

        #region Private Functions 自用函数

        #endregion
    }
}